<template>
  <a-layout class="dept-list-wrap">
    <a-layout-sider style="width: auto; min-width: 240px">
      <div class="dept-header flex-c-sb">
        <span style="font-size: 16px">组织架构</span>
        <a-button type="outline" size="mini" @click="showEditDialog = true">添加部门</a-button>
      </div>
      <a-tree class="dept-tree-w" :default-selected-keys="defaultSelectedKeys" :data="deptList" @select="clickDeptNode" :block-node="true" :field-names="{ key: 'id' }" :virtualListProps="{ height: '100%' }">
        <template #title="nodeData">
          <span>{{ nodeData.deptName }}</span>
          <span>（{{ userNumMap[nodeData.id] || 0 }}）</span>
        </template>
        <template #extra="nodeData">
          <div class="flex-c edit-icon-w" v-if="nodeData.parentId">
            <icon-edit class="dept-svg" style="margin-right: 5px" @click="openEditDept(nodeData)" />
            <icon-delete class="dept-svg" @click="deleteEditDept(nodeData.id)" />
          </div>
        </template>
      </a-tree>
    </a-layout-sider>
    <a-layout class="user-list-w table-gl-w">
      <a-layout-header class="user-header">
        <p class="dept-name">
          <span>{{ currentDeptNode.deptName }}</span>
          <span>（{{ userNumMap[currentDeptNode.id] || 0 }}）</span>
        </p>
        <div class="flex-c-sb">
          <div class="flex-c">
            <p style="margin-right: 15px">部门编号：{{ currentDeptNode.deptCode }}</p>
            <p>
              <span>部门主管：</span>
              <template v-for="(user, i) in deptManagers" :key="i">
                <span>{{ user.userName }}</span>
                <span v-if="i < deptManagers.length - 1">，</span>
              </template>
            </p>
            <icon-settings class="icon" @click="showManagersDialog = true" />
            <p style="margin-left: 30px">
              <span>跨部门成员：</span>
              <template v-for="(user, i) in deptOtherUser" :key="i">
                <span>{{ user.userName }}</span>
                <span v-if="i < deptOtherUser.length - 1">，</span>
              </template>
            </p>
            <icon-settings class="icon" @click="showOtherUserDialog = true" />
          </div>
          <!-- <a-button type="primary" size="small" @click="showEditDialog = true">添加成员</a-button> -->
        </div>
      </a-layout-header>
      <div class="line"></div>
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
      </div>
      <div class="line"></div>
      <TableWrap style="flex: 1" @refresh="getUserListByDept">
        <template #headerLeft>
          <a-button type="primary" size="medium" @click="showEditUserDialog = true">添加成员</a-button>
        </template>
        <template #tableBody>
          <a-table class="show-border-table" :loading="tableLoading" :columns="tableColumns" :data="userList" size="mini" :scroll="{ y: '100%' }" :pagination="false">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.title === '姓名'" #cell="{ record }">
                  <p>
                    <span>{{ record.userName }}</span>
                  </p>
                  <p class="highlight">{{ record.employeeNumber }}</p>
                </template>
                <template v-else-if="item.title === '入职日期'" #cell="{ record }">
                  <p>{{ $setTime(record.enrollmentDate, 'YYYY-MM-DD') }}</p>
                </template>
                <template v-else-if="item.title === '角色'" #cell="{ record }">
                  <a-popover position="bottom">
                    <template v-for="(role, i) in record.roleList">
                      <p v-if="i < 2" :key="role">
                        <span>{{ role.roleName }}</span>
                        <span v-if="i == 1 && record.roleList.length > 2">...</span>
                      </p>
                    </template>
                    <template #content>
                      <p v-for="role in record.roleList" :key="role">{{ role.roleName }}</p>
                    </template>
                  </a-popover>
                </template>
                <template v-else-if="item.title === '登录'" #cell="{ record }">
                  <a-switch v-model="record[item.dataIndex]" :disabled="record.depart" @change="changeLoginAble($event, record)">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </template>
                <template v-else-if="item.title === '在职状态'" #cell="{ record }">
                  <p>{{ record.depart ? '离职' : '在职' }}</p>
                </template>
                <template v-else-if="item.title === '操作'" #cell="{ record }">
                  <a-space>
                    <a-button type="text" size="mini" @click="openEditUser(record)">编辑</a-button>
                    <a-button v-if="!record.depart" type="text" size="mini" @click="changeJobState(record)">离职</a-button>
                  </a-space>
                </template>
                <template v-else #cell="{ record }">
                  {{ record[item.dataIndex] }}
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </a-layout>
  </a-layout>
  <!-- 编辑/添加部门 -->
  <a-modal v-model:visible="showEditDialog" :title="currentDept.id ? '编辑部门' : '添加部门'" title-align="start" :mask-closable="false" :on-before-ok="submitDept" :ok-loading="submitLoading" @cancel="closedEditDept">
    <a-form ref="deptFormRef" :model="currentDept" :rules="rules">
      <a-form-item v-if="currentDept.id" field="id" label="部门ID">
        <p>{{ currentDept.id }}</p>
      </a-form-item>
      <a-form-item field="deptName" label="部门名称">
        <a-input v-model="currentDept.deptName" placeholder="" :max-length="10" allow-clear show-word-limit />
      </a-form-item>
      <a-form-item field="deptCode" label="部门编号">
        <a-input v-model="currentDept.deptCode" placeholder="请输入大写字母或数字" allow-clear />
      </a-form-item>
      <a-form-item field="parentId" label="上级部门">
        <a-cascader v-model="currentDept.parentId" :options="deptList" placeholder="请选择" :field-names="{ value: 'id', label: 'deptName' }" check-strictly />
      </a-form-item>
      <a-form-item field="post" label="部门主管">
        <a-select v-model="currentDept.userIds" multiple allow-clear>
          <a-option v-for="(item, index) in allUserList" :key="index" :value="item.id">{{ item.userName }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="开启独立核算" v-if="currentDept.id">
        <a-space v-if="!$extract(companyWalletInfo, 'consumeWalletAccount.id')">
          <a-switch @change="startWalletCom">
            <template #checked> 开 </template>
            <template #unchecked> 关 </template>
          </a-switch>
          <div style="font-size: 12px; color: #a39999">一旦开启独立核算就无法关闭，系统会给该部门生成一套独立核算账户</div>
        </a-space>
        <div v-else>
          <div>消费账户：{{ $extract(companyWalletInfo, 'consumeWalletAccount.code') }}</div>
          <div>体现账户：{{ $extract(companyWalletInfo, 'withdrawWalletAccount.code') }}</div>
        </div>
      </a-form-item>
    </a-form>
    <a-alert v-if="currentDept.id" type="warning">请谨慎修改，不建议频繁修改组织信息.</a-alert>
  </a-modal>
  <!-- 添加编辑用户 -->
  <AddUser v-if="showEditUserDialog" :isShow="showEditUserDialog" :currenData="currentUser" :roleList="roleList" :deptList="deptList" @closed="closedEditUser" @success="updateSuccess" />
  <!-- 选择主管 -->
  <ChooseUser v-if="showManagersDialog" title="部门主管" :defaultData="deptManagers.map((el) => el.id)" :list="allUserList" :multiple="true" :isShow="showManagersDialog" :isRequired="false" @closed="showManagersDialog = false" @success="updateManagers" />
  <!-- 选择跨部门成员 -->
  <ChooseUser v-if="showOtherUserDialog" title="跨部门成员" :defaultData="deptOtherUser.map((el) => el.id)" :list="allUserList" :multiple="true" :isShow="showOtherUserDialog" :isRequired="false" @closed="showOtherUserDialog = false" @success="updateOthers" />
</template>
<script lang="ts" setup>
  import { Message, Modal } from '@arco-design/web-vue'
  import { defineComponent, ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import { delateMenuChildren } from '@/utils'
  import { findCompanyWallet } from '@/api/finance/wallet'
  import useUserStore from '@/store/modules/user'
  import * as system from '@/api/system'
  import ChooseUser from '@/components/ChooseUser.vue'
  import AddUser from './components/addUser.vue'
  onMounted(async () => {
    getAllUserList()
    getRoleList()
    await getOrganization()
    getOrganizeNum()
  })
  const userInfo = useUserStore()
  const deptList = ref<any>([])
  const showEditDialog = ref(false) //打开编辑部门弹窗
  const currentDept = ref<{ [propName: string]: any }>({}) //当前编辑部门信息
  const currentDeptNode = ref<{ [propName: string]: any }>({}) //当前选中部门节点
  const deptManagers = ref<Array<any>>([]) //部门主管
  const deptOtherUser = ref<Array<any>>([]) //部门其他人员
  const userList = ref<Array<any>>([]) //用户列表
  const allUserList = ref<Array<any>>([]) //所有用户列表
  const tableLoading = ref(false)
  let pageNation = ref({ pageSize: 20, pageNum: 1, total: 0 }) //分页
  const showEditUserDialog = ref(false) //打开编辑用户弹窗
  const currentUser = ref<{ [propName: string]: any }>({}) //当前编辑用户信息
  const showManagersDialog = ref(false) //选择主管
  const showOtherUserDialog = ref(false) //选择跨部门成员
  const submitLoading = ref(false)
  const defaultSelectedKeys = ref<Array<string>>([])
  const roleList = ref<any>([]) //角色列表
  let companyWalletInfo: any = ref({})

  const deptFormRef = ref()
  const rules = ref({
    deptName: [
      { required: true, message: '请输入部门名称' },
      { maxLength: 10, message: '部门名称最多10个字' },
    ],
    deptCode: [{ required: true, message: '请输入部门编号' }],
    parentId: [{ required: true, message: '请选择上级部门' }],
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'userName',
      keyItems: [
        { label: '姓名', value: 'userName' },
        { label: '用户名', value: 'loginName' },
        { label: '手机号', value: 'mobile' },
      ],
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'roleId',
      label: '已授权角色',
      width: 180,
      value: ref(),
      type: 'select_multiple',
      optionItems: [],
    },
    {
      key: 'loginAble',
      label: '登录状态',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '允许',
          value: 'true',
        },
        {
          label: '禁止',
          value: 'false',
        },
      ],
    },
    {
      key: 'depart',
      label: '在职状态',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [
        {
          label: '在职',
          value: 'false',
        },
        {
          label: '离职',
          value: 'true',
        },
      ],
    },
    {
      key: 'enrollmentDate',
      label: '入职日期',
      value: ref(),
      type: 'date_range',
      width: 240,
      attrs: {
        placeholder: ['入职开始日期', '入职结束日期'],
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const tableColumns: Array<any> = [
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '用户名',
      dataIndex: 'loginName',
    },
    {
      title: '入职日期',
      dataIndex: 'enrollmentDate',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '岗位',
      dataIndex: 'position',
    },
    {
      title: '角色',
      dataIndex: 'roleList',
    },
    {
      title: '登录',
      dataIndex: 'loginAble',
    },
    {
      title: '在职状态',
      dataIndex: 'depart',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 90,
    },
  ]
  // 获取角色列表
  async function getRoleList() {
    const res: any = await system.findRoleListByParam()
    if (!res?.data?.length) return
    roleList.value = res.data || []
    filterItem.value[1].optionItems = roleList.value.map((el: any) => {
      return {
        value: el.id,
        label: el.roleName,
      }
    })
  }
  // 获取所有用户列表
  async function getAllUserList() {
    const res: any = await system.getOrganizesUser({
      // depart: false,
      pageNum: 1,
      pageSize: 1000,
    })
    allUserList.value = res?.data?.records || []
  }

  //获取组织架构数据
  async function getOrganization() {
    deptList.value = []
    const res: any = await system.getOrganizes()
    if (!res?.data?.length) return
    deptList.value = delateMenuChildren(res.data)
    // 默认选中的节点
    if (currentDeptNode.value.id) {
      defaultSelectedKeys.value = [currentDeptNode.value.id]
    } else {
      defaultSelectedKeys.value = [deptList.value[0].id]
      clickDeptNode(deptList.value[0].id, deptList.value[0])
    }
  }
  // 获取组织架构人数
  const userNumMap = ref<any>({})
  async function getOrganizeNum() {
    userNumMap.value = {}
    const res: any = await system.getOrganizeUserNum({})
    res?.data?.forEach((el: any) => {
      userNumMap.value[el.deptId] = el.userNum
    })
  }
  // 选中部门
  function clickDeptNode(key: any, item: any) {
    currentDeptNode.value = item?.node || item
    getDeptManagersList(currentDeptNode.value.id)
    getDeptOtherList(currentDeptNode.value.id)
    getUserListByDept()
  }
  // 获取部门管理员
  async function getDeptManagersList(deptId: string) {
    const res: any = await system.getDeptManagers({ deptId })
    deptManagers.value = res?.data || []
  }
  // 获取部门其他人员
  async function getDeptOtherList(deptId: string) {
    const res: any = await system.getDeptOther({ deptId })
    deptOtherUser.value = res?.data || []
  }
  // 当前部门用户列表
  async function getUserListByDept(filterData?: any) {
    let params = {
      deptId: currentDeptNode.value.id,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
      needRole: true,
      ...filterData,
    }
    tableLoading.value = true
    const res: any = await system.getOrganizesUser(params)
    tableLoading.value = false
    userList.value = res?.data?.records || []
    pageNation.value.total = res?.data?.total || 0
  }
  // 分页
  function changePage(val: number) {
    pageNation.value.pageNum = val
    getUserListByDept()
  }
  function sizeChange(val: number) {
    pageNation.value.pageSize = val
    getUserListByDept()
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    pageNation.value.pageNum = 1
    let filterData = JSON.parse(JSON.stringify(info)) || {}
    filterData.startDate = filterData?.enrollmentDate?.[0]
    filterData.endDate = filterData?.enrollmentDate?.[1]
    delete filterData.enrollmentDate
    getUserListByDept(filterData)
  }

  // 编辑部门
  async function openEditDept(data: any) {
    currentDept.value.id = data.id
    currentDept.value.deptName = data.deptName
    currentDept.value.deptCode = data.deptCode
    currentDept.value.ownerCompanyId = data.companyId
    currentDept.value.parentId = data.parentId
    currentDept.value.userIds = data.userIds
    const res: any = await system.getDeptManagers({ deptId: currentDeptNode.value.id })
    currentDept.value.userIds = res?.data?.map((el: any) => el.id) || []
    console.log(currentDept.value.userIds)
    showEditDialog.value = true
    isStart(data)
  }

  // 是否开启独立核算
  const isStart = async (info: any) => {
    let params = {
      companyId: userInfo.companyId,
      groupId: info.id,
    }
    const res: any = await findCompanyWallet(params)
    companyWalletInfo.value = res.data
  }
  // 删除部门
  function deleteEditDept(id: string) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除此部门吗？',
      cancelText: '取消',
      okText: '删除',
      onOk: async () => {
        let res: any = await system.deleteDept({ idList: [id] })
        if (res) {
          Message.success('数据删除成功')
          if (id === currentDeptNode.value.id) {
            currentDeptNode.value = {}
          }
          getOrganization()
        }
      },
    })
  }
  // 关闭编辑部门弹窗
  function closedEditDept() {
    currentDept.value = {}
    deptFormRef.value.clearValidate()
    showEditDialog.value = false
  }
  // 提交部门信息
  async function submitDept() {
    let valid = await deptFormRef.value.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let res: any
    if (currentDept.value.id) {
      res = await system.updateDept(currentDept.value)
    } else {
      res = await system.createDept(currentDept.value)
    }
    if (!res) return false
    Message.success('保存成功')
    getOrganization()
    closedEditDept()
    return true
  }
  // 更新部门主管
  async function updateManagers(user: any) {
    const res: any = await system.updateDeptManagers({
      deptId: currentDeptNode.value.id,
      userIds: user,
    })
    if (res) {
      Message.success('保存成功')
      getDeptManagersList(currentDeptNode.value.id)
    }
  }
  // 更新跨部门人员
  async function updateOthers(user: any) {
    const res: any = await system.updateDeptOthers({
      deptId: currentDeptNode.value.id,
      userIds: user,
    })
    if (res) {
      Message.success('保存成功')
      getDeptOtherList(currentDeptNode.value.id)
    }
  }
  // 编辑成员
  function openEditUser(data: any) {
    currentUser.value = JSON.parse(JSON.stringify(data))
    currentUser.value.roleIds = data?.roleList?.map((el: any) => el.id)
    showEditUserDialog.value = true
  }
  function closedEditUser() {
    currentUser.value = {}
    showEditUserDialog.value = false
  }
  function updateSuccess(type: string) {
    currentUser.value = {}
    showEditUserDialog.value = false
    if (type == 'add') {
      getOrganizeNum()
    }
    getUserListByDept()
  }
  // 设置离职
  function changeJobState(user: any) {
    Modal.confirm({
      title: '设置离职',
      content: `请再次确认，将${user.userName}设置为已离职`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        const res: any = await system.updateUser({
          id: user.id,
          depart: true,
        })
        if (res) {
          Message.success('已设为离职')
          getUserListByDept()
        }
      },
    })
  }
  // 修改登录状态
  async function changeLoginAble(loginAble: any, user: any) {
    const res: any = await system.updateUser({
      id: user.id,
      loginAble: loginAble,
    })
    if (res) {
      getUserListByDept()
    }
  }

  const startWalletCom = async (val: boolean) => {
    if (val) {
      let params = {
        groupId: currentDept.value.id,
        groupName: currentDept.value.deptName,
        ownerId: currentDept.value.id,
        ownerName: currentDept.value.deptName,
      }
      const res: any = await system.initWallterAccounts(params)
      if (res) {
        Message.success('开启独立核算成功')
        isStart(currentDept.value)
      }
    }
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'UserList',
  })
</script>
<style lang="less" scoped>
  .dept-list-wrap {
    height: calc(100vh - @menuHeight);
    padding: 5px;
    .dept-tree-w {
      height: calc(100vh - 142px);
      color: #666;
      :deep(.arco-tree-node) {
        justify-content: center;
        color: var(--color-text-2);
        &:hover {
          .edit-icon-w {
            display: flex;
          }
        }
      }
      .edit-icon-w {
        position: absolute;
        right: 10px;
        top: 10px;
        display: none;
        .dept-svg {
          font-size: 15px;
          &:hover {
            color: #3370ff;
          }
        }
      }
    }
    .dept-header {
      padding: 10px;
    }
    .user-list-w {
      margin-left: 5px;
      background-color: #fff;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      height: 100%;
      .user-header {
        padding: 10px;
        color: var(--color-text-2);
        .icon {
          margin-left: 10px;
          cursor: pointer;
          font-size: 16px;
          &:hover {
            color: #3370ff;
          }
        }
        .dept-name {
          font-size: 15px;
          margin-bottom: 5px;
          font-weight: bold;
        }
      }
      .line {
        height: 5px;
        width: 100%;
        background-color: #f0f2f5;
      }
      .search-w {
        padding: 10px 10px 0;
      }
    }
    :deep(.arco-table-td) {
      height: 56px;
    }
  }
</style>
